﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using DBStatusViewerGateway;

namespace ComputingEngine
{
    public partial class MainForm : Form
    {
        private NotifyIcon _notifyIcon;
        private Gateway _gateway;
        private System.Windows.Forms.Timer _timer;

        public MainForm()
        {
            InitializeComponent();

            uxProgressBar.Minimum = 0;
            uxProgressBar.Maximum = 100;

            _notifyIcon = new NotifyIcon();
            _notifyIcon.Icon = Properties.Resources.appico;
            _notifyIcon.Visible = true;
            _notifyIcon.DoubleClick += new EventHandler(_notifyIcon_DoubleClick);

            this.SizeChanged += new EventHandler(MainForm_SizeChanged);
            uxMinimize.Click += new EventHandler(uxMinimize_Click);
            uxExit.Click += new EventHandler(uxExit_Click);

            _gateway = new Gateway();


            _timer = new System.Windows.Forms.Timer();
            _timer.Tick += new EventHandler(_timer_Tick);
            _timer.Interval = 2000;
            _timer.Start();
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            var output = _gateway.GetStatus();
            if (output == null)
                return;
            uxDbComplete.Text = string.Format("{0}/{1}", output.DBIndex, output.DBCount);
            uxDatabase.Text = output.BuiltDB;
            uxProcessName.Text = output.ProcessName;
            uxProgress.Text = string.Format("{0}%", output.Percent);
            uxProgressBar.Value = output.Percent < 0 ? 0 : output.Percent;
        }

        void uxExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void uxMinimize_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        void _notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }    
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            _timer.Stop();
            _notifyIcon.Visible = false;
            _notifyIcon.Dispose();

            base.OnClosing(e);
        }
    }
}
